/**
 * src/utils/identityUtils.ts
 * ------------------------------------
 * 身份与亲密度系统工具函数
 * 1. getFamilyIdentities：获取所有家人身份配置
 * 2. getFriendIdentities：获取所有朋友身份配置
 * 3. getIdentityInfo：根据身份子类型获取身份信息
 * 4. getIntimacyLevel：根据亲密度数值获取等级
 * 5. calculateIntimacyPoints：计算亲密度增加点数
 * 6. checkUnlockConditions：检查解锁条件
 * 提供身份系统相关的所有工具函数，不直接修改状态
 * 创建日期：2025-08-06
 */
import Taro from '@tarojs/taro'
import { 
  IdentityType, 
  IntimacyLevel, 
  IntimacyRecordType,
  IntimacyRecord,
  UserIdentity,
  UnlockedContent
} from '../types/identity'
import { 
  IDENTITY_CONFIG, 
  FAMILY_SPECIAL_DISHES, 
  FRIEND_STICKER_STORIES,
  INTIMACY_RULES,
  INTIMACY_LEVELS,
  SPECIAL_HOLIDAYS
} from '../config/identityConfig'
import { CloudDataManager } from './cloud'

/**
 * 身份管理工具类 - 提供身份与亲密度系统的核心功能
 */
export class IdentityUtils {
  
  /**
   * 获取身份配置信息
   * @param identitySubType 身份子类型
   * @returns IdentityInfo | null 身份配置信息，如果不存在则返回null
   */
  static getIdentityInfo(identitySubType: string) {
    return IDENTITY_CONFIG[identitySubType] || null
  }

  /**
   * 获取所有家人身份
   * @returns IdentityInfo[] 家人身份列表
   */
  static getFamilyIdentities() {
    return Object.values(IDENTITY_CONFIG).filter(
      identity => identity.type === IdentityType.FAMILY
    )
  }

  /**
   * 获取所有好友身份
   * @returns IdentityInfo[] 好友身份列表
   */
  static getFriendIdentities() {
    return Object.values(IDENTITY_CONFIG).filter(
      identity => identity.type === IdentityType.FRIEND
    )
  }

  /**
   * 根据亲密度获取等级
   * @param intimacy 亲密度数值
   * @returns IntimacyLevel 亲密度等级
   */
  static getIntimacyLevel(intimacy: number): IntimacyLevel {
    if (intimacy >= 91) return IntimacyLevel.FAMILY
    if (intimacy >= 61) return IntimacyLevel.CLOSE
    if (intimacy >= 31) return IntimacyLevel.FRIEND
    if (intimacy >= 11) return IntimacyLevel.ACQUAINTANCE
    return IntimacyLevel.STRANGER
  }

  /**
   * 获取亲密度等级名称
   * @param level 亲密度等级
   * @returns string 等级名称
   */
  static getIntimacyLevelName(level: IntimacyLevel): string {
    return INTIMACY_LEVELS[level]?.name || '未知'
  }

  /**
   * 增加用户亲密度
   * @param userId 用户ID
   * @param type 记录类型（点餐、评价等）
   * @param points 增加的点数
   * @param description 描述信息
   * @returns Promise<boolean> 是否成功增加亲密度
   */
  static async addIntimacy(
    userId: string, 
    type: IntimacyRecordType, 
    points: number, 
    description: string
  ): Promise<boolean> {
    try {
      // 创建亲密度记录
      const record: Omit<IntimacyRecord, 'id'> = {
        userId,
        type,
        points,
        description,
        createdAt: new Date()
      }

      // 保存到云数据库
      await CloudDataManager.addData('intimacy_records', record)

      // 更新用户亲密度
      const user = await CloudDataManager.getData('users', userId)
      if (user) {
        const newIntimacy = Math.min(100, (user.intimacy || 0) + points)
        await CloudDataManager.updateData('users', userId, {
          intimacy: newIntimacy,
          intimacyLevel: this.getIntimacyLevel(newIntimacy),
          lastInteractionDate: new Date()
        })

        // 检查是否解锁新内容
        await this.checkUnlocks(userId, newIntimacy, user.identitySubType)
      }

      return true
    } catch (error) {
      console.error('增加亲密度失败:', error)
      return false
    }
  }

  /**
   * 检查是否解锁新内容
   * @param userId 用户ID
   * @param intimacy 当前亲密度
   * @param identitySubType 身份子类型
   * @returns Promise<void>
   */
  static async checkUnlocks(userId: string, intimacy: number, identitySubType: string): Promise<void> {
    try {
      // 检查家人特殊菜品
      const familyDishes = FAMILY_SPECIAL_DISHES.filter(
        dish => dish.requiredIdentity === identitySubType && dish.requiredIntimacy <= intimacy
      )

      for (const dish of familyDishes) {
        const isUnlocked = await this.isContentUnlocked(userId, dish.id, 'special_dish')
        if (!isUnlocked) {
          await this.unlockContent(userId, dish.id, 'special_dish')
          this.showUnlockNotification(dish.dishName, dish.unlockMessage)
        }
      }

      // 检查好友贴图故事
      const friendStories = FRIEND_STICKER_STORIES.filter(
        story => story.requiredIdentity === identitySubType && story.requiredIntimacy <= intimacy
      )

      for (const story of friendStories) {
        const isUnlocked = await this.isContentUnlocked(userId, story.id, 'sticker_story')
        if (!isUnlocked) {
          await this.unlockContent(userId, story.id, 'sticker_story')
          this.showUnlockNotification(story.stickerName, `解锁了${story.stickerName}！`)
        }
      }
    } catch (error) {
      console.error('检查解锁失败:', error)
    }
  }

  /**
   * 检查内容是否已解锁
   * @param userId 用户ID
   * @param contentId 内容ID
   * @param contentType 内容类型（特殊菜品或贴图故事）
   * @returns Promise<boolean> 是否已解锁
   */
  static async isContentUnlocked(
    userId: string, 
    contentId: string, 
    contentType: 'special_dish' | 'sticker_story'
  ): Promise<boolean> {
    try {
      const unlocked = await CloudDataManager.getAllData('unlocked_contents', {
        userId,
        contentId,
        contentType
      })
      return unlocked.length > 0
    } catch (error) {
      console.error('检查解锁状态失败:', error)
      return false
    }
  }

  /**
   * 解锁内容
   * @param userId 用户ID
   * @param contentId 内容ID
   * @param contentType 内容类型
   * @returns Promise<boolean> 是否成功解锁
   */
  static async unlockContent(
    userId: string, 
    contentId: string, 
    contentType: 'special_dish' | 'sticker_story'
  ): Promise<boolean> {
    try {
      const unlockedContent: Omit<UnlockedContent, 'id'> = {
        userId,
        contentId,
        contentType,
        unlockedAt: new Date(),
        isUsed: false
      }

      await CloudDataManager.addData('unlocked_contents', unlockedContent)
      return true
    } catch (error) {
      console.error('解锁内容失败:', error)
      return false
    }
  }

  /**
   * 显示解锁通知
   * @param title 通知标题
   * @param message 通知消息
   */
  static showUnlockNotification(title: string, message: string) {
    Taro.showModal({
      title: `🎉 解锁成功：${title}`,
      content: message,
      showCancel: false,
      confirmText: '太棒了！'
    })
  }

  /**
   * 获取用户可解锁的内容
   * @param userId 用户ID
   * @param intimacy 当前亲密度
   * @param identitySubType 身份子类型
   * @returns Promise<{ specialDishes: any[], stickerStories: any[] }> 可解锁的内容列表
   */
  static async getUpcomingUnlocks(
    userId: string, 
    intimacy: number, 
    identitySubType: string
  ) {
    const specialDishes = FAMILY_SPECIAL_DISHES.filter(
      dish => dish.requiredIdentity === identitySubType && dish.requiredIntimacy > intimacy
    )

    const stickerStories = FRIEND_STICKER_STORIES.filter(
      story => story.requiredIdentity === identitySubType && story.requiredIntimacy > intimacy
    )

    return { specialDishes, stickerStories }
  }

  /**
   * 获取用户已解锁的内容
   * @param userId 用户ID
   * @returns Promise<{ specialDishes: any[], stickerStories: any[] }> 已解锁的内容列表
   */
  static async getUnlockedContents(userId: string) {
    try {
      const unlocked = await CloudDataManager.getAllData('unlocked_contents', { userId })
      
      const specialDishes = FAMILY_SPECIAL_DISHES.filter(dish =>
        unlocked.some(u => u.contentId === dish.id && u.contentType === 'special_dish')
      )

      const stickerStories = FRIEND_STICKER_STORIES.filter(story =>
        unlocked.some(u => u.contentId === story.id && u.contentType === 'sticker_story')
      )

      return { specialDishes, stickerStories }
    } catch (error) {
      console.error('获取已解锁内容失败:', error)
      return { specialDishes: [], stickerStories: [] }
    }
  }

  /**
   * 检查是否为特殊节日
   * @returns { isHoliday: boolean, holidayName?: string, intimacy?: number } 节日信息
   */
  static checkSpecialHoliday() {
    const today = new Date()
    const monthDay = `${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
    
    const holiday = SPECIAL_HOLIDAYS.find(h => h.date === monthDay)
    
    return {
      isHoliday: !!holiday,
      holidayName: holiday?.name,
      intimacy: holiday?.intimacy
    }
  }

  /**
   * 处理用户操作增加亲密度
   * @param userId 用户ID
   * @param action 操作类型
   * @param description 描述信息
   * @returns Promise<boolean> 是否成功增加亲密度
   */
  static async processIntimacyAction(
    userId: string, 
    action: IntimacyRecordType, 
    description: string
  ): Promise<boolean> {
    const points = INTIMACY_RULES[action] || 0
    if (points > 0) {
      return await this.addIntimacy(userId, action, points, description)
    }
    return false
  }
}

// 导出实例
export const identityUtils = {
  getIdentityInfo: IdentityUtils.getIdentityInfo,
  getFamilyIdentities: IdentityUtils.getFamilyIdentities,
  getFriendIdentities: IdentityUtils.getFriendIdentities,
  getIntimacyLevel: IdentityUtils.getIntimacyLevel,
  getIntimacyLevelName: IdentityUtils.getIntimacyLevelName,
  addIntimacy: IdentityUtils.addIntimacy,
  checkUnlocks: IdentityUtils.checkUnlocks,
  isContentUnlocked: IdentityUtils.isContentUnlocked,
  unlockContent: IdentityUtils.unlockContent,
  showUnlockNotification: IdentityUtils.showUnlockNotification,
  getUpcomingUnlocks: IdentityUtils.getUpcomingUnlocks,
  getUnlockedContents: IdentityUtils.getUnlockedContents,
  checkSpecialHoliday: IdentityUtils.checkSpecialHoliday,
  processIntimacyAction: IdentityUtils.processIntimacyAction
} 